package response;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

/**
 * @author Mc.Chai
 * @program: JavaWeb
 * @create 2022-03-22-21:23 21:23
 */
@WebServlet("/checkCode")
public class CheckCode extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int width=100;
        int height=50;
        /**创建一个验证码图片对象*/
        BufferedImage bufferedImage = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);

        /**填充背景颜色*/
        //创建一个画笔对象
        Graphics graphics = bufferedImage.getGraphics();
        graphics.setColor(Color.pink);
        graphics.fillRect(0,0,width,height);
        /**画边框*/
        graphics.setColor(Color.blue);
        graphics.drawRect(0,0,width-1,height-1);//或矩形
        /**写验证码*/
        String str="1234567890qwertyuioplkjhgfdsazxcvbnm";
        Random random = new Random();
        for (int i = 1; i <=4; i++) {
            //生成[0,str.length()-1)的数字
            int j = random.nextInt(str.length());
            //找到str中j的下标，默认从0开始，str.charAt(0)=1
            char c = str.charAt(j);
            graphics.drawString(c+"",width/5*i,height/2);//画字符
        }
        /**画干扰线*/
        graphics.setColor(Color.green);
        for (int i = 0; i < 8; i++) {
            graphics.drawLine(random.nextInt(width),random.nextInt(height),random.nextInt(width),random.nextInt(height));
        }


        /**将图片展示到页面*/
        ImageIO.write(bufferedImage,"jpg",response.getOutputStream());
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }
}
